package com.example.rwq_test.leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 最长子串
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2023/11/14
 */
public class LengthOfLongestSubstring {
    public static void main(String[] args) {
        String s = "rwqqwronwc";
        System.out.println(lengthOfLongestSubstring1(s));
    }

    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }

        int maxLength = 0;
        int right = 0;
        int left = 0;
        Set<Character> set = new HashSet<>();

        while (right < s.length()) {
            if (!set.contains(s.charAt(right))) {
                set.add(s.charAt(right++));
                maxLength = Math.max(set.size(), maxLength);
            } else {
                set.remove(s.charAt(left++));
            }
        }
        return maxLength;
    }

    public static int lengthOfLongestSubstring1(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        Map<Character,Integer> map = new HashMap<>();
        int left = -1;
        int maxLength = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                left = Math.max(left, map.get(s.charAt(i)));
            }
            maxLength = Math.max(maxLength, i - left);
            map.put(s.charAt(i), i);
        }
        return maxLength;
    }
}
